﻿using System;
using System.Collections;
using System.ComponentModel;

using Spencen.Mobile.UI.Primitives;
using Spencen.Mobile.UI.Templating;
using Spencen.Mobile.UI.Layout;

namespace Spencen.Mobile.UI.Controls
{
    public class ItemsControl : DrawingContainer
    {
        private IList _items;

        public ItemsControl( IDrawingHost host ) : base( host )
        {
            IsInitializing = true;
            var defaultItems = new ObservableList();
            Items = defaultItems;
            LayoutEngine = new StackLayout();
            IsInitializing = false;
        }

        public IList Items 
        {
            get { return _items; }
            set
            {
                if ( _items is ObservableList )
                    ( (ObservableList)_items ).ItemsChanged -= Items_ItemsChanged;
                
                _items = value;
                
                if ( _items is ObservableList )
                    ( (ObservableList)_items ).ItemsChanged += Items_ItemsChanged;

                CreateChildren();
            }
        }

        public IDataTemplate ItemTemplate { get; set; }

        private void Items_ItemsChanged( object sender, ListChangedEventArgs e )
        {
            if ( IsInitializing ) return;

            switch ( e.ListChangedType )
            {
                case ListChangedType.ItemAdded:
                    var childElement = CreateTemplate( Items[ e.NewIndex ] );
                    Children.Insert( e.NewIndex, childElement );
                    break;

                case ListChangedType.ItemDeleted:
                    Children.RemoveAt( e.NewIndex );
                    break;

                case ListChangedType.Reset:
                    Children.Clear();
                    foreach ( var item in Items )
                    {
                        var iterationElement = CreateTemplate( item );
                        Children.Add( iterationElement );
                    }
                    break;
            }
            Invalidate();
        }

        private DrawingElement CreateTemplate( object dataItem )
        {
            var template = ItemTemplate;
            if ( template == null )
                template = new DefaultDataTemplate();

            return template.ApplyTemplate( Host, dataItem );
        }

        public override void EndInit()
        {
            base.EndInit();
            CreateChildren();
        }

        private void CreateChildren()
        {
            Items_ItemsChanged( this, new ListChangedEventArgs( ListChangedType.Reset, 0 ) );
        }
    }
}
